<template>
  <div>
    <a-form-model ref="ha_userForm" :rules="rules" :model="ha_user">
      <a-form-model-item :label-col="labelCol" :wrapper-col="wrapperCol" label="用户名" prop="fullname" has-feedback>
        <a-input v-if="!isView" allow-clear v-model="ha_user.fullname" :maxLength="30" placeholder="请输入用户名" />
        <span v-text="ha_user.fullname" v-else></span>
      </a-form-model-item>

      <a-form-model-item :label-col="labelCol" :wrapper-col="wrapperCol" label="性别" prop="gender" has-feedback>
        <a-select v-if="!isView" v-model="ha_user.gender" style="width: 110px" placeholder="请输入性别">
          <a-select-option :value="1"> 男 </a-select-option>
          <a-select-option :value="0"> 女 </a-select-option>
        </a-select>

        <span v-text="ha_user.gender == 0 ? '女' : '男'" v-else></span>
      </a-form-model-item>

      <a-form-model-item :label-col="labelCol" :wrapper-col="wrapperCol" prop="avatar" label="头像">
        <span v-if="!isView">
          <a-upload
            name="avatar"
            list-type="picture-card"
            class="avatar-uploader"
            :show-upload-list="false"
            accept=".png, .jpg, .jpeg"
            :before-upload="beforeUpload"
            @change="handleChange"
            :customRequest="customRequest"
          >
            <img v-if="ha_user.avatar" :src="ha_user.avatar" style="width: 100%" />
            <div v-else>
              <a-icon :type="loading ? 'loading' : 'plus'" />
              <div class="ant-upload-text">上传图片</div>
            </div>
          </a-upload>
          <span style="color: blue; display: inline-block">*注：点击图片可重新上传</span>
        </span>
        <img style="width: 111px; height: 86px" :src="ha_user.avatar" v-else />
      </a-form-model-item>

      <a-form-model-item
        :label-col="labelCol"
        :wrapper-col="wrapperCol"
        label="密码"
        prop="password"
        v-if="!hidden"
        has-feedback
      >
        <a-input allow-clear v-model="ha_user.password" :maxLength="13" placeholder="请输入密码" />
      </a-form-model-item>

      <a-form-model-item
        :label-col="labelCol"
        :wrapper-col="wrapperCol"
        label="手机号码"
        prop="mobile"
        :maxLength="11"
        has-feedback
      >
        <a-input v-if="!isView" allow-clear v-model="ha_user.mobile" placeholder="请输入手机号码" />
        <span v-text="ha_user.mobile" v-else></span>
      </a-form-model-item>
      <a-form-model-item :label-col="labelCol" :wrapper-col="wrapperCol" label="座机" prop="telephone" has-feedback>
        <a-input v-if="!isView" allow-clear v-model="ha_user.telephone" :maxLength="13" placeholder="请输入座机" />
        <span v-text="ha_user.telephone" v-else></span>
      </a-form-model-item>
      <a-form-model-item :label-col="labelCol" :wrapper-col="wrapperCol" label="电子邮箱" prop="email" has-feedback>
        <a-input v-if="!isView" allow-clear v-model="ha_user.email" :maxLength="50" placeholder="请输入电子邮箱">
        </a-input>
        <span v-text="ha_user.email" v-else></span>
      </a-form-model-item>
      <a-form-model-item>
        <div style="text-align: center">
          <a-button :style="{ marginRight: '8px' }" icon="close" @click="onClose"> 关闭 </a-button>
          <a-button :style="{ marginRight: '8px' }" icon="reload" @click="resetForm" v-if="!isView"> 重置 </a-button>
          <a-button type="primary" @click="onSubmit" icon="save" :loading="loading" v-if="!isView"> 保存 </a-button>
        </div>
      </a-form-model-item>
    </a-form-model>
  </div>
</template>
<script>
/* eslint-disable */
import { saveHa_user, viewHa_user } from '@/api/base/ha_user'
// 没用到附件请删除
import { minioUpload } from '@/api/base/file'
function getBase64(img, callback) {
  const reader = new FileReader()
  reader.addEventListener('load', () => callback(reader.result))
  reader.readAsDataURL(img)
}
/**
 * 文件大小 字节转换单位
 * @param size
 * @returns {string|*}
 */
function getFileSize(size) {
  if (!size) return ''
  if (size < pow1024(1)) return size + 'B'
  if (size < pow1024(2)) return (size / pow1024(1)).toFixed(2) + 'KB'
  if (size < pow1024(3)) return (size / pow1024(2)).toFixed(2) + 'MB'
  if (size < pow1024(4)) return (size / pow1024(3)).toFixed(2) + 'GB'
  return (size / pow1024(4)).toFixed(2) + 'TB'
}
export default {
  data() {
    return {
      imageUrl: '', //预览的base64图片编码
      fileMaxSize: '5', //允许上传的最大MB
      selecetModel: {
        email: 1,
      },
      labelCol: { span: 6 }, // label宽
      wrapperCol: { span: 18 }, // 组件宽
      // 没用到附件请删除
      defaultFileList: [
        {
          uid: '1',
          name: 'xxx.png',
          status: 'done',
          response: 'Server Error 500', // custom error message to show
          url: 'http://192.168.2.118:9000/power/2020-08-25/202008250150270b643a1fefd54845b4cd5e6ec9ea47f3.jpg',
        },
      ],
      previewVisible: false, // 展示上传按钮,没有用到附件请删除
      previewImage: '', // 预览图片,没有用到附件请删除
      // 没有用到附件请删除
      imgList: [
        {
          uid: '-1',
          name: '猫猫.jpg',
          status: 'done',
          url: 'http://192.168.2.118:9000/power/2020-08-25/202008250150270b643a1fefd54845b4cd5e6ec9ea47f3.jpg',
        },
      ],
      loading: false, //按钮显示
      isView: false, //是否查看
      ha_user: {
        id: '',
        username: '',
        fullname: '',
        password: '',
        gender: 1,
        avatar: '',
        mobile: '',
        telephone: '',
        email: '',
        deleted: '',
      }, //用户信息
      rules: {
        id: [{ required: true, message: '请输入id!', trigger: 'change' }],
        fullname: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { max: 30, message: '用户名请控制在30字以内', trigger: 'blur' },
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 8, max: 40, message: '密码请控制在8-40字母之间', trigger: 'blur' },
        ],
        gender: [{ required: true, message: '请选择性别', trigger: 'change' }],
        mobile: [
          /*           { message: '电话号码仅能输入数字', trigger: 'blur', type: 'number' }, */
          { max: 11, message: '请输入11位的电话号码,', trigger: 'blur' },
        ],
        telephone: [{ max: 13, message: '座机号请控制在13个号码以内', trigger: 'blur' }],
        email: [{ max: 50, message: '邮箱请控制在30字母以内', trigger: 'blur' }],
      },
      hidden: false,
    }
  },
  created() {},
  //watch
  methods: {
    /**
     * 上传素材文件
     */
    handleChange(info) {
      if (info.file.status === 'uploading') {
        this.loading = true
        return
      }
      if (info.file.status === 'done') {
        getBase64(info.file.originFileObj, (imageUrl) => {
          this.imageUrl = imageUrl
          this.loading = false
        })
      } else {
        this.loading = false
      }
    },
    /**
     * 素材上传之前校验文件大小及类型
     */
    beforeUpload(file) {
      let isAcceptType = ''
      let isLtSize = file.size / 1024 / 1024 < this.fileMaxSize
      if (!isLtSize) {
        this.$message.warning('请上传' + this.fileMaxSize + 'MB以内的文件')
      }
      return isAcceptType && isLtSize
    },
    /**
     * 调用父组件的方法收起抽屉
     */
    onClose() {
      this.$emit('close')
    },
    /**
     * 提供给父组件调用
     * 点击新增进入时重置表单数据
     */
    resetHa_user() {
      this.isView = false
      this.resetForm()
    },
    /**
     * 提供给父组件调用
     * 查询用户信息
     */
    findHa_userById(id, isView, hidden) {
      this.isView = isView
      console.log('hidden', hidden)
      this.hidden = hidden || false
      console.log('hidden', this.hidden)
      this.resetForm()

      viewHa_user(id).then((res) => {
        this.ha_user = res.data
        /**
         *  枚举如果不能显示中文打开下面的代码
         */
      })
    },
    /**
     * 重置表单
     */
    resetForm() {
      this.$refs.ha_userForm.resetFields()
    },
    /**
     * 提交表单
     */
    onSubmit() {
      this.$refs.ha_userForm.validate((valid) => {
        this.loading = true
        if (valid) {
          delete this.ha_user.primaryKey
          console.log('submit!', this.ha_user)
          const savem = this.$message.loading('数据正在保存中...', 0)
          // if (this.selecetModel.email == '1') {
          //   this.ha_user.email = this.ha_user.email + '@qq.co'
          // }
          // this.ha_user.email = this.ha_user.email + this.selecetModel.email
          saveHa_user(this.ha_user).then((res) => {
            if (res.code !== 0) {
              setTimeout(savem, 0)
              this.$message.error('用户保存失败')
              this.loading = false
            } else {
              setTimeout(savem, 0)
              this.$message.success('保存成功')
              this.$emit('reloadList')
              this.$emit('close')
              this.loading = false
            }
          })
        } else {
          this.loading = false
          // 加延时器的目的是为了vue实例更新未完成，我们可能获取DOM失败的问题
          // 利用原生js的方式，获取所有失败的类名，获得一个数组，取第一个元素获取焦点
          setTimeout(() => {
            const isError = document.getElementsByClassName('has-error')
            const input = isError[0].querySelector('input')
            //console.log(input)
            if (input !== null && input !== 'undefind' && input !== '') {
              isError[0].querySelector('input').focus()
                ? isError[0].querySelector('input').focus()
                : isError[0].querySelector('input').click()
            } else {
              isError[0].querySelector('textarea').focus()
            }
          }, 10)
          return false
        }
      })
    },
    /**
     * 取消预览,没有用到附件请删除
     */
    handleImgCancel() {
      this.previewVisible = false
    },
    /**
     * 预览图片,没有用到附件请删除
     */
    async handleImgPreview(file) {
      if (!file.url && !file.preview) {
        file.preview = await getBase64(file.originFileObj)
      }
      this.previewImage = file.url || file.preview
      this.previewVisible = true
    },
    /**
     * 图片改变,没有用到附件请删除
     */
    imgChange({ fileList }) {
      this.imgList = fileList
    },
    /**
     * 附件改变,没有用到附件请删除
     */
    fileChange({ file, fileList }) {
      if (file.status !== 'uploading') {
        console.log(file, fileList)
      }
    },
    /**
     * 自定义上传方法,没有用到附件请删除
     */
    customRequest(data) {
      console.log('customRequest', data)
      this.uploadFile(data)
    },
    /**
     * 上传附件,没有用到附件请删除
     */
    uploadFile(data) {
      console.log(data)
      minioUpload(data.file).then((res) => {
        console.log('minioUpload-res', res)
        this.formFile = data.file
        if (res.code !== 0) {
          data.onError()
          this.loading = false
          this.$message.error(res.msg)
        } else {
          data.onSuccess()
          this.ha_user.avatar = res.data.url
          let file = {
            uid: res.data.id,
            name: res.data.filename,
            status: 'done',
            url: res.data.url,
            flag: data.file.uid,
          }
          // console.log('data.file',data.file)
          if (this.tabIndex == 0) {
            //更新链接封面图
            this.ha_user.avatar = res.data.url
            this.news.uid = res.data.id
          } else {
            //更新文件信息
            this.file = {
              uid: res.data.id,
              fileName: data.file.name,
              fileSize: getFileSize(data.file.size),
              url: res.data.url,
            }
          }
        }
      })
    },
  },
}
</script>


<style lang="less" src="@/style/base.less">
.avatar-uploader > .ant-upload {
  width: 128px;
  height: 128px;
}
</style>